<template>
    <view class="voice-button-wrapper">
        <!-- 语音按钮 -->
        <view 
            class="voice-btn" 
            :class="{ 'recording': isCurrentRecording }"
            @touchstart="handleTouchStart"
            @touchend="handleTouchEnd"
            @touchcancel="handleTouchCancel"
        >
            <image class="voice-icon" src="/static/img/consolePages/voice-icon.png" mode="widthFix"></image>
            <text class="voice-text">{{ isCurrentRecording ? '正在录音中' : '长按语音转文字' }}</text>
        </view>

        <!-- 语音录制动画弹窗 -->
        <view v-if="showVoiceModal" class="voice-modal" @click="stopVoiceInput">
            <view class="voice-modal-content">
                <view class="voice-modal-title">转文字 • 普通话</view>
                <view class="waveform-container">
                    <view class="waveform">
                        <view 
                            v-for="(bar, index) in waveformBars" 
                            :key="index"
                            class="waveform-bar"
                            :style="{ height: bar + 'rpx' }"
                        ></view>
                    </view>
                </view>
                <view class="voice-modal-tip">松开发送</view>
            </view>
        </view>

        <!-- 预览文本悬浮显示 -->
        <view v-if="previewText && showVoiceModal" class="preview-floating">
            <text>{{ previewText }}</text>
        </view>
    </view>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue';
import { useVoiceRecognitionStore } from '@/store/voiceRecognition';

// 定义组件属性
const props = defineProps({
    // 当前输入框的值，用于追加文本
    currentValue: {
        type: String,
        default: ''
    },
    // 长按触发时间（毫秒）
    longPressDelay: {
        type: Number,
        default: 500
    }
});

// 定义事件
const emit = defineEmits(['update']);

// 使用 Pinia store
const voiceStore = useVoiceRecognitionStore();

// 为每个组件实例创建唯一标识
const componentId = Math.random().toString(36).substr(2, 9);

// 本地状态
let isTouching = false;
let longPressTimer = null;

// 计算属性 - 从 store 获取状态
const isCurrentRecording = computed(() => voiceStore.isCurrentComponentRecording(componentId));
const showVoiceModal = computed(() => voiceStore.showModal);
const waveformBars = computed(() => voiceStore.waveformData);
const previewText = computed(() => voiceStore.previewText);

// 监听识别结果变化
watch(() => voiceStore.recognitionResult, (newResult) => {
    if (newResult && voiceStore.currentComponentId === componentId) {
        // 将识别结果追加到输入框
        const currentText = props.currentValue;
        const newValue = currentText + (currentText ? ' ' : '') + newResult;
        emit('update', newValue);
        
        // 清除结果，避免重复触发
        voiceStore.clearResult();
    } else if (newResult) {
        // 收到识别结果但不是当前组件
    }
});

// 处理触摸开始
const handleTouchStart = () => {
    isTouching = true;
    
    // 清除之前的定时器
    if (longPressTimer) {
        clearTimeout(longPressTimer);
    }
    
    // 设置长按定时器
    longPressTimer = setTimeout(() => {
        if (isTouching) {
            startVoiceInput();
        }
    }, props.longPressDelay);
};

// 处理触摸结束
const handleTouchEnd = () => {
    isTouching = false;
    
    // 清除长按定时器
    if (longPressTimer) {
        clearTimeout(longPressTimer);
        longPressTimer = null;
    }
    
    // 如果正在录音，则停止
    if (voiceStore.isCurrentComponentRecording(componentId)) {
        stopVoiceInput();
    }
};

// 处理触摸取消
const handleTouchCancel = () => {
    isTouching = false;
    
    // 清除长按定时器
    if (longPressTimer) {
        clearTimeout(longPressTimer);
        longPressTimer = null;
    }
    
    // 如果正在录音，则停止
    if (voiceStore.isCurrentComponentRecording(componentId)) {
        stopVoiceInput();
    }
};

// 开始语音输入
const startVoiceInput = () => {
    voiceStore.startRecording(componentId);
};

// 停止语音输入
const stopVoiceInput = () => {
    // 检查当前组件是否在录音
    if (voiceStore.isCurrentComponentRecording(componentId)) {
        if (previewText.value && previewText.value.length > 0) {
            // 等待最终结果
            voiceStore.waitForFinalResult();
        } else {
            voiceStore.stopRecording();
        }
    }
};

// 组件挂载时初始化事件监听器和注册组件
onMounted(() => {
    // 注册组件
    voiceStore.registerComponent();
});

// 组件销毁时清理
onUnmounted(() => {
    // 清除定时器
    if (longPressTimer) {
        clearTimeout(longPressTimer);
    }
    
    // 注销组件
    voiceStore.unregisterComponent(componentId);
});
</script>

<style lang="scss" scoped>
.voice-button-wrapper {
    // 组件容器，可以根据需要调整样式
}

.voice-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(255, 255, 255, 0.1);
    padding: 10rpx;
    color: #fff;
    font-size: 28rpx;
    transition: all 0.3s ease;
    
    &.recording {
        border-color: #ff4757;
        animation: pulse 1s infinite;
    }
}

@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.02); }
    100% { transform: scale(1); }
}

.voice-icon {
    width: 18rpx;
    height: 26rpx;
    margin-right: 10rpx;
}

.voice-text {
    color: #fff;
}

// 语音录制弹窗
.voice-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: flex-end;
    z-index: 1000;
}

.voice-modal-content {
    width: 100%;
    background: #fff;
    border-radius: 32rpx 32rpx 0 0;
    padding: 60rpx 40rpx 80rpx;
    text-align: center;
}

.voice-modal-title {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 60rpx;
}

.waveform-container {
    display: flex;
    justify-content: center;
    margin-bottom: 60rpx;
}

.waveform {
    display: flex;
    align-items: center;
    gap: 4rpx;
    height: 120rpx;
    position: relative;
}

.waveform::before {
    content: '';
    position: absolute;
    left: 0;
    right: 0;
    top: 50%;
    height: 2rpx;
    background: repeating-linear-gradient(
        to right,
        #ccc 0,
        #ccc 4rpx,
        transparent 4rpx,
        transparent 8rpx
    );
    transform: translateY(-50%);
}

.waveform-bar {
    width: 6rpx;
    background: linear-gradient(to top, #666, #999);
    border-radius: 3rpx;
    transition: height 0.1s ease;
    position: relative;
    z-index: 1;
}

.voice-modal-tip {
    font-size: 28rpx;
    color: #666;
}

.preview-floating {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: #fff;
    color: #66ccff;
    padding: 20rpx 40rpx;
    border-radius: 16rpx;
    font-size: 36rpx;
    font-weight: bold;
    z-index: 10000;
    white-space: nowrap;
    max-width: 80%;
    text-align: center;
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.3);
}
</style> 